import { coordinates } from "~/constants/coordinates";
import { task1s } from "~/constants/tasks";

export const playersConfig = [
  {
    name: '红色方',
    color: 'red',
  },
  {
    name: '蓝色方',
    color: 'blue',
  }
]

interface IHistoryTaskItem {
  chessIndex: number
  playerIndex: number
}

const defaultPlayerCount = 2
const diceTimer = 1200
const chessTimer = 300

export function useFlight() {
  const dataStore = useLocalStorage('flightStore', {
    tasks: task1s,
    historyTasks: Array(defaultPlayerCount).fill(0).map((_, index) => ({ chessIndex: 0, playerIndex: index })) as IHistoryTaskItem[],
    playerCount: defaultPlayerCount,
    currentPlayerIndex: 0,
    step: 1,
  })

  const flightState = useState('flightState', () => ({
    dice: 6,
    diceRolling: false,
    currentChesses: [] as IHistoryTaskItem[],
    isMoving: false,
  }))

  const { dice, diceRolling, isMoving, currentChesses } = toRefs(flightState.value)

  const isGameStarted = computed(() => dataStore.value.historyTasks.some(item => item.chessIndex > 0))

  function rollDice() {
    if (diceRolling.value || isMoving.value) {
      return;
    }
    if (isGameOver()) {
      showConfirmDialog({
        title: '游戏结束',
        message: '是否重新开始游戏？',
      }).then(() => {
        initGame()
        rollDice()
      }).catch(() => {})
      return
    }
    diceRolling.value = true
    dice.value = getRandomDice()
    console.log('dice: ', dice.value)
    setTimeout(() => {
      diceRolling.value = false
      moving()
    }, diceTimer)
  }

  function getRandomDice() {
    const diceStep = Math.max(dataStore.value.step - 1, 0);
    // 权重分布：step 越大，1点权重越高，6点权重越低
    const weights = [1, 2, 3, 4, 5, 6].map(i => 1 + (6 - i) * diceStep);
    const totalWeight = weights.reduce((sum, w) => sum + w, 0);
    const rand = Math.floor(Math.random() * totalWeight);
    let acc = 0;
    for (let i = 0; i < weights.length; i++) {
      acc += weights[i];
      if (rand < acc) {
        return i + 1;
      }
    }
    return 6; // 理论不会走到这里，兜底
  }

  function initGame() {
    dataStore.value.historyTasks = Array(dataStore.value.playerCount).fill(0).map((_, index) => ({ chessIndex: 0, playerIndex: index }))
    dataStore.value.currentPlayerIndex = 0
    dice.value = 6
    initCurrentChesses()
  }

  function initCurrentChesses() {
    const chesses: IHistoryTaskItem[] = [];
    for (let i = dataStore.value.historyTasks.length - 1; i >= 0; i--) {
      const item = dataStore.value.historyTasks[i]
      if (chesses.some(chess => chess.playerIndex === item.playerIndex)) {
        continue
      }
      chesses.push(item)
      if (chesses.length === dataStore.value.playerCount) {
        break
      }
    }
    currentChesses.value = chesses
  }

  function moving() {
    flightState.value.isMoving = true
    const currentPlayerHistoryTask = JSON.parse(JSON.stringify(dataStore.value.historyTasks.findLast(item => item.playerIndex === dataStore.value.currentPlayerIndex)!)) as IHistoryTaskItem
    if (currentPlayerHistoryTask.chessIndex + dice.value >= coordinates.length) {
      currentPlayerHistoryTask.chessIndex = coordinates.length - 1
    } else {
      currentPlayerHistoryTask.chessIndex += dice.value
    }
    dataStore.value.historyTasks.push(currentPlayerHistoryTask)
    console.log('dataStore.value.historyTasks: ', dataStore.value.historyTasks)
    const currentChessItem = currentChesses.value.find(item => item.playerIndex === dataStore.value.currentPlayerIndex)
    const timer = setInterval(() => {
      if (currentChessItem?.chessIndex === currentPlayerHistoryTask.chessIndex) {
        clearInterval(timer)
        flightState.value.isMoving = false
        const player = playersConfig[dataStore.value.currentPlayerIndex]
        showDialog({
          title: currentPlayerHistoryTask.chessIndex === coordinates.length - 1 ? `${player.name}完成了所有任务` : `${player.name}的回合`,
          message: dataStore.value.tasks[currentPlayerHistoryTask.chessIndex] + (isGameOver() ? '\n恭喜你们完成了所有任务!' : ''),
        })
        dataStore.value.currentPlayerIndex = getNextPlayerIndex()
        return
      }
      currentChessItem!.chessIndex++
    }, chessTimer)
  }

  function getNextPlayerIndex() {
    if (dataStore.value.historyTasks.every(item => item.chessIndex === coordinates.length - 1 || item.playerIndex === dataStore.value.currentPlayerIndex)) {
      return dataStore.value.currentPlayerIndex
    }
    const nextPlayerIndex = (dataStore.value.currentPlayerIndex + 1) % dataStore.value.playerCount
    if (dataStore.value.historyTasks.find(item => item.playerIndex === nextPlayerIndex)!.chessIndex === coordinates.length - 1) {
      return getNextPlayerIndex()
    }
    return nextPlayerIndex
  }

  function isGameOver() {
    return dataStore.value.historyTasks.every(item => item.chessIndex === coordinates.length - 1)
  }

  function setPlayerCount(count: number) {
    showConfirmDialog({
      title: '确认',
      message: `确定要改为${count}人游戏并重新开始吗？`,
    }).then(() => {
      dataStore.value.playerCount = count
      dataStore.value.historyTasks = Array(count).fill(0).map((_, index) => ({ chessIndex: 0, playerIndex: index }))
    }).catch(() => {})
  }

  return {
    flightState,
    diceRolling,
    dice,
    coordinates,
    dataStore,
    isMoving,
    currentChesses,
    isGameStarted,
    initGame,
    rollDice,
    setPlayerCount,
    initCurrentChesses,
  }
}

